﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;

namespace WholeSlideImageViewer.Services
{
    internal class AddressService : IAddressService
    {
        private readonly IServer _server;

        public AddressService(IServer server)
        {
            _server = server;
        }

        public bool TryGetAccessAddress([NotNullWhen(true)] out Uri? uri)
        {
            IServerAddressesFeature? feature = _server.Features.Get<IServerAddressesFeature>();
            if (feature is null)
            {
                uri = null;
                return false;
            }
            string address = feature.Addresses.FirstOrDefault();
            if (address is null)
            {
                uri = null;
                return false;
            }
            return Uri.TryCreate(address, UriKind.Absolute, out uri);
        }

    }
}
